//
// Created by pedro on 18-10-22.
//

#include "merge_sort.h"

void merge(int *data, int begin, int mid, int end) {
    int i = begin, j = mid, k = 0;
    int *tmp = (int *) malloc(sizeof(int) * (end - begin));
    for (; i < mid && j < end; tmp[k++] = (data[i] < data[j] ? data[i++] : data[j++]));
    for (; i < mid; tmp[k++] = data[i++]);
    for (; j < end; tmp[k++] = data[j++]);
    for (i = begin, k = 0; i < end; data[i++] = tmp[k++]);
    free(tmp);
}

void merge_sort(int *data, int begin, int end) {
    if (end - begin < 2)return;
    int mid = (begin + end) >> 1;
    merge_sort(data, begin, mid);
    merge_sort(data, mid, end);
    merge(data, begin, mid, end);
}
